package xnsq

import (
	"encoding/json"
	"fmt"
	"strings"

	"gitee.com/xiaoyutab/xgotool/https"
	"gitee.com/xiaoyutab/xgotool/optional/xlog"
	"gitee.com/xiaoyutab/xgotool/xerror"
	"gitee.com/xiaoyutab/xgotool/xnum"
	"gitee.com/xiaoyutab/xgotool/xstring"
)

// 延时HTTP请求
type HttpsQuestStruct struct {
	URL    string            `json:"url"`    // 请求网址
	Method string            `json:"method"` // 请求方式：GET/POST/POSTJSON
	Param  any               `json:"param"`  // 请求携带参数，参考https.Post或者https.PostJson中的param
	Header map[string]string `json:"header"` // 请求携带的header头
}

// 直接延时请求HTTPS接口协议
//
//	NSQ	xnsq.https.quest	<HttpsQuestStruct>
func httpsQuest(p []byte) error {
	tmp := HttpsQuestStruct{}
	if err := json.Unmarshal(p, &tmp); err != nil {
		return err
	}
	if tmp.URL == "" {
		return xlog.CE("待请求网址为空", nil)
	}
	if len(tmp.URL) <= 4 || tmp.URL[0:4] != "http" {
		return xlog.CE("带请求网址并非正常http网址", xerror.New(tmp.URL))
	}
	method := []string{"GET", "POST", "POSTJSON"}
	if !xnum.InArray(strings.ToUpper(tmp.Method), method) {
		return xlog.CE("请求方式不在允许范围内", xerror.New(tmp.Method))
	}
	var curl *https.CURL
	switch strings.ToUpper(tmp.Method) {
	case "GET":
		pm := map[string]string{}
		xstring.Any2any(tmp.Param, pm)
		curl = https.Get(tmp.URL, pm, tmp.Header)
	case "POST":
		pm := map[string]string{}
		xstring.Any2any(tmp.Param, pm)
		curl = https.Post(tmp.URL, pm, tmp.Header)
	case "POSTJSON":
		pm := map[string]any{}
		xstring.Any2any(tmp.Param, pm)
		curl = https.PostJson(tmp.URL, pm, tmp.Header)
	}
	if curl.Error != nil {
		return xlog.CE("httpsQuest队列请求失败", curl.Error)
	}
	if curl.HttpCode != 200 {
		return xlog.CE("网址返回代码不是200", fmt.Errorf("当前网址 %s 返回代码：%d", tmp.URL, curl.HttpCode))
	}
	return nil
}
